package com.jcfk.eam.service.base;

import com.jcfk.eam.domain.dto.base.EamSopItemImgDTO;
import com.jcfk.eam.domain.dto.base.EamSopStandardImgDTO;
import com.jcfk.eam.domain.po.base.EamSopItem;
import com.jcfk.eam.domain.po.base.EamSopItemImg;
import com.jcfk.eam.domain.po.base.EamSopStandardImg;
import com.jcfk.eam.domain.query.base.EamSopItemQuery;
import com.jcfk.eam.domain.dto.base.EamSopItemDTO;
import com.jcfk.eam.domain.dto.base.EamSopItemValueDTO;
import com.jcfk.eam.domain.po.base.EamSopItemValue;
import com.jcfk.eam.dao.base.EamSopItemDao;
import com.jcfk.common.business.service.BaseService;
import com.jcfk.common.web.domain.DataPage;
import com.jcfk.common.web.domain.RetResult;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.stereotype.Service;

import org.springframework.transaction.annotation.Transactional;
import org.springframework.beans.factory.annotation.Autowired;
import com.jcfk.common.core.utils.BeanUtils;
import cn.hutool.core.util.StrUtil;
import com.jcfk.common.security.utils.SecurityUtils;
import com.alibaba.druid.util.StringUtils;

import static com.jcfk.common.core.utils.BeanUtils.convertList;

import java.util.*;

import java.util.stream.Collectors;

/**
 * 标准作业项
 *
 * @author awei
 * @email 522891237@gqq.com
 * @date 2024-08-08
 */
@Service
public class EamSopItemService extends BaseService<EamSopItemDao, EamSopItem> {


    @Autowired
    private EamSopItemValueService eamSopItemValueService;

    @Autowired
    private EamSopItemImgService sopItemImgService;

    /**
     * EamSopItem分页查询
     *
     * @param page  分页设置
     * @param query 查询条件
     * @return 分页查询结果
     */
    public DataPage<EamSopItemDTO> queryByPage(DataPage<EamSopItemDTO> page, EamSopItemQuery query) {
        // 分页查询
        query.setSopItemCode(StringUtils.isEmpty(query.getSopItemCode()) ? query.getSopItemCode() : query.getSopItemCode() + "%");
        query.setSopItemName(StringUtils.isEmpty(query.getSopItemName()) ? query.getSopItemName() : query.getSopItemName() + "%");
        query.setSopItemMethod(StringUtils.isEmpty(query.getSopItemMethod()) ? query.getSopItemMethod() : query.getSopItemMethod() + "%");
        query.setSopItemTool(StringUtils.isEmpty(query.getSopItemTool()) ? query.getSopItemTool() : query.getSopItemTool() + "%");
        page = this.baseMapper.queryByPage(page, query);
        return page;
    }

    /**
     * 根据条件获取单表信息列表
     *
     * @param query 查询条件
     * @return List<EamSopItemDTO>
     */
    public List<EamSopItemDTO> getList(EamSopItemQuery query) {
        // 查询条件
        QueryWrapper<EamSopItem> qw = new QueryWrapper<>();
        qw.lambda().like(!StrUtil.isEmpty(query.getSopItemCode()), EamSopItem::getSopItemCode, query.getSopItemCode());
        qw.lambda().eq(!StrUtil.isEmpty(query.getStandardId()), EamSopItem::getStandardId, query.getStandardId());
        qw.lambda().like(!StrUtil.isEmpty(query.getSopItemName()), EamSopItem::getSopItemName, query.getSopItemName());
        qw.lambda().like(!StrUtil.isEmpty(query.getSopItemMethod()), EamSopItem::getSopItemMethod, query.getSopItemMethod());
        qw.lambda().like(!StrUtil.isEmpty(query.getSopItemTool()), EamSopItem::getSopItemTool, query.getSopItemTool());
        qw.lambda().eq(EamSopItem::getDeleted, 0);
        // 查询数据
        List<EamSopItem> list = super.list(qw);

        List<EamSopItemDTO> dtoList = convertList(list, EamSopItemDTO.class);

        List<String> ids = dtoList.stream().map(EamSopItemDTO::getId).collect(Collectors.toList());

        if (ids.size() > 0) {
            QueryWrapper<EamSopItemImg> queryWrapper = new QueryWrapper<>();
            queryWrapper.lambda().in(EamSopItemImg::getSopItemId, ids);

            List<EamSopItemImg> imgList = sopItemImgService.list(queryWrapper);

            List<EamSopItemImgDTO> dtos = convertList(imgList, EamSopItemImgDTO.class);

            Map<String, List<EamSopItemImgDTO>> iamges = new HashMap<>();

            // 将节点按照父节点进行分组
            for (EamSopItemImgDTO node : dtos) {
                String id = node.getSopItemId();
                iamges.computeIfAbsent(id, k -> new ArrayList<>()).add(node);
            }

            // 查询条件
            QueryWrapper<EamSopItemValue> eamSopItemValueQueryWrapper = new QueryWrapper<>();
            eamSopItemValueQueryWrapper.lambda().eq(!StrUtil.isEmpty(query.getId()), EamSopItemValue::getSopItemId, query.getId());

            // 查询数据
            List<EamSopItemValue> values = eamSopItemValueService.list(eamSopItemValueQueryWrapper);
            List<EamSopItemValueDTO> eamSopItemValueDTOS = convertList(values, EamSopItemValueDTO.class);


            Map<String, List<EamSopItemValueDTO>> eammaps = new HashMap<>();
            // 将节点按照父节点进行分组
            for (EamSopItemValueDTO node : eamSopItemValueDTOS) {
                String id = node.getSopItemId();
                eammaps.computeIfAbsent(id, k -> new ArrayList<>()).add(node);
            }

            for (EamSopItemDTO sopItemDTO : dtoList) {
                sopItemDTO.setDetails(eammaps.get(sopItemDTO.getId()));
                sopItemDTO.setImages(iamges.get(sopItemDTO.getId()));
            }
        }


        return dtoList;
    }

    /**
     * 获取根据关联id详情表列表
     *
     * @param query 查询条件
     * @return List<EamSopItemDTO>
     */
    public List<EamSopItemValueDTO> getDetails(EamSopItemQuery query) {
        // 查询条件
        QueryWrapper<EamSopItemValue> qw = new QueryWrapper<>();
        qw.lambda().eq(!StrUtil.isEmpty(query.getId()), EamSopItemValue::getSopItemId, query.getId());

        // 查询数据
        List<EamSopItemValue> list = eamSopItemValueService.list(qw);

        return convertList(list, EamSopItemValueDTO.class);
    }


    /**
     * 判断EamSopItem是已经存在
     *
     * @param dto
     * @return
     */
    public RetResult<String> isValid(EamSopItemDTO dto) {
        QueryWrapper<EamSopItem> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(EamSopItem::getSopItemCode, dto.getSopItemCode());
        queryWrapper.lambda().eq(EamSopItem::getStandardId, dto.getStandardId());
        queryWrapper.eq("deleted", 0);

        if (!StringUtils.isEmpty(dto.getId())) queryWrapper.ne("id", dto.getId());
        Integer count = this.count(queryWrapper);

        if (count > 0) return RetResult.fail("标准作业编号已存在");

        return RetResult.ok();
    }

    /**
     * 插入标准作业项
     *
     * @param dto 插入对象
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public void insert(EamSopItemDTO dto) {

        // 保存
        EamSopItem item = new EamSopItem();
        BeanUtils.copyProperties(dto, item);
        this.setDefaultValue(item);

        super.save(item);

        // 设置关联主键
        for (EamSopItemValueDTO detail : dto.getDetails()) {
            detail.setSopItemId(item.getId());
        }

        // 保存明细表
        eamSopItemValueService.saveBatch(dto.getDetails(), item.getId());


        List<EamSopItemImg> files = new ArrayList<>();
        for (EamSopItemImgDTO imgae : dto.getImages()) {
            EamSopItemImg eamSopStandardImg = new EamSopItemImg();
            eamSopStandardImg.setSopItemId(item.getId());
            eamSopStandardImg.setUrl(imgae.getUrl());
            eamSopStandardImg.setFileType(imgae.getFileType());
            eamSopStandardImg.setFilename(imgae.getFilename());
            eamSopStandardImg.setOriginalfilename(imgae.getOriginalfilename());
            eamSopStandardImg.setPath(imgae.getPath());
            sopItemImgService.setDefaultValue(eamSopStandardImg);
            files.add(eamSopStandardImg);
        }

        if (files.size() > 0) sopItemImgService.saveBatch(files);
    }


    /**
     * 更新标准作业项
     *
     * @param dto 更新对象
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public void update(EamSopItemDTO dto) {

        // 保存
        EamSopItem item = new EamSopItem();
        BeanUtils.copyProperties(dto, item);

        // 默认数据
        this.setDefaultValue(item);

        super.updateById(item);

        // 设置关联主键
        for (EamSopItemValueDTO detail : dto.getDetails()) {
            detail.setSopItemId(item.getId());
        }
        // 保存明细表
        eamSopItemValueService.saveBatch(dto.getDetails(), item.getId());

        QueryWrapper<EamSopItemImg> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(EamSopItemImg::getSopItemId, dto.getId());
        sopItemImgService.remove(queryWrapper);

        List<EamSopItemImg> files = new ArrayList<>();
        for (EamSopItemImgDTO imgae : dto.getImages()) {
            EamSopItemImg eamSopStandardImg = new EamSopItemImg();
            eamSopStandardImg.setSopItemId(item.getId());
            eamSopStandardImg.setUrl(imgae.getUrl());
            eamSopStandardImg.setFileType(imgae.getFileType());
            eamSopStandardImg.setFilename(imgae.getFilename());
            eamSopStandardImg.setOriginalfilename(imgae.getOriginalfilename());
            eamSopStandardImg.setPath(imgae.getPath());
            sopItemImgService.setDefaultValue(eamSopStandardImg);
            files.add(eamSopStandardImg);
        }

        if (files.size() > 0) sopItemImgService.saveBatch(files);
    }


    /**
     * 根据批量主键删除标准作业项(逻辑删除)
     *
     * @param dto
     * @return bool
     */
    @Transactional(rollbackFor = Exception.class)
    public Boolean logicDeleteList(EamSopItemDTO dto) {

        EamSopItem item = new EamSopItem();

        this.setDefaultValue(item);
        item.setVersion(dto.getVersion());
        item.setDeleted(1);

        QueryWrapper<EamSopItem> queryWrapper = new QueryWrapper<>();
        queryWrapper.in("id", dto.getIds());

        return this.update(item, queryWrapper);
    }

    /**
     * 设置添加默认值
     *
     * @param item 添加对象
     */
    public void setDefaultValue(EamSopItem item) {
        if (StrUtil.isEmpty(item.getCreatedUserId())) {
            item.setCreatedUserId(SecurityUtils.getUserId());
            item.setCreateTime(new Date());
            item.setVersion(1L);
            item.setDeleted(0);
            item.setCreatedUserName(SecurityUtils.getUserName());
        }
        item.setLastUpdatedUserId(SecurityUtils.getUserId());
        item.setLastUpdateTime(new Date());

        item.setLastUpdatedUserName(SecurityUtils.getUserName());
    }


    /**
     * 根据主键获取标准作业项信息
     *
     * @param id 主键
     * @return StandardCodeDTO
     */
    public EamSopItemDTO get(String id) {
        // 查询数据
        EamSopItem item = this.baseMapper.selectById(id);
        EamSopItemDTO dto = new EamSopItemDTO();
        try {
            BeanUtils.copyProperties(item, dto);
        } catch (RuntimeException e) {
            throw e;
        }

        QueryWrapper<EamSopItemImg> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(EamSopItemImg::getSopItemId, dto.getId());
        List<EamSopItemImg> list = sopItemImgService.list(queryWrapper);
        dto.setImages(convertList(list, EamSopItemImgDTO.class));

        return dto;
    }


    /**
     * 根据主键获取标准作业项信息
     *
     * @param id 主键
     * @return StandardCodeDTO
     */
    public void deleteitem(String id) {
        EamSopItem item = getById(id);
        this.setDefaultValue(item);
        item.setDeleted(1);

        this.updateById(item);
    }
}

